package net.dgg.liuyinglong.plugin.actions;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import net.dgg.liuyinglong.plugin.Andr;
import net.dgg.liuyinglong.plugin.FileTools;
import net.dgg.liuyinglong.plugin.MFinal;
import net.dgg.liuyinglong.plugin.forms.PluginDialogUseCase;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * UseCase创建
 */
public class PluginUseCase extends AnAction {
    private Project project;
    /**
     * 包名
     * 对应$PackageName$
     */
    private String PackageName = "";
    /**
     * 插件域名
     * $DomianName$
     */
    private String DomianName = "Temp";
    /**
     * 对应类名
     * $ClassName$
     */
    private String ClassName = "";
    /**
     * Json类型
     * $JsonType$
     */
    private String JsonType = "";
    /**
     * 接口名称
     * $JkName$
     */
    private String JkName = "";
    /**
     * 请求方式
     */
    private String NetType = "";
    /**
     * 请求参数
     */
    private String NetParams = "";
    /**
     * usecase 输出目录
     */
    private String outDir = "";


    @Override
    public void actionPerformed(AnActionEvent e) {
        project = e.getData(PlatformDataKeys.PROJECT);
        PackageName = Andr.getPackageName(project);
        outDir = getAppPath();
        init();
        refreshProject(e);
    }

    /**
     * 初始化Dialog
     */
    private void init() {
        if (!"".equals(Andr.getPackageName(project))) {
            String[] dnames = Andr.getPackageName(project).split("\\.");
            DomianName = FileTools.toUpperCaseFirstOne(dnames[dnames.length - 1]);
            PluginDialogUseCase myDialog = new PluginDialogUseCase((name, jsonType, jkName, netType, netParams) -> {
                ClassName = name;
                JsonType = jsonType;
                JkName = jkName;
                NetType = netType;
                NetParams = netParams;
                createClassFile();
//                Messages.showInfoMessage(project, "创建成功", "提示");
            });
            myDialog.setLocationRelativeTo(null);
            myDialog.setSize(400, 300);
            myDialog.setVisible(true);
        }
    }

    /**
     * 创建类
     */
    private void createClassFile() {
        String content = readTemplateFile("TemplateUseCase.java.ft");
        content = dealTemplateContent(content);
        FileTools.writeToFile(content, outDir, ClassName + "UseCase.java");
    }

    /**
     * 刷新项目
     *
     * @param e
     */
    private void refreshProject(AnActionEvent e) {
        e.getProject().getBaseDir().refresh(false, true);
    }


    /**
     * 替换模板中字符
     *
     * @param content
     * @return
     */
    private String dealTemplateContent(String content) {
        content = content.replace("$PackageName$", PackageName);
        content = content.replace("$DomianName$", DomianName);
        content = content.replace("$ClassName$", ClassName);
        content = content.replace("$JsonType$", JsonType);
        content = content.replace("$_netParams$", NetParams);
        content = content.replace("$INC_PARAMS$", getIncParams());
        content = content.replace("$INC_EXEC$", getIncExec());
        return content;
    }

    private List<String> params = new ArrayList<>();

    private String getIncParams() {
        //page=1&limit=1&loginUserId=1&customerPhone=1&keyWord=1
        if (!"".equals(NetParams)) {
            params.clear();
            String[] jx0 = NetParams.split("&");
            for (int i = 0; i < jx0.length; i++) {
                String[] jx1 = jx0[i].split("=");
                params.add(jx1[0]);
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < params.size(); i++) {
                sb.append("public int " + params.get(i) + ";");
                sb.append("\n");
            }
//            sb.append("public Request(");
//            for (int i = 0; i < params.size(); i++) {
//                if (i != 0) {
//                    sb.append(",");
//                    sb.append("\n");
//                }
//                sb.append(" String " + params.get(i));
//            }
//            sb.append(")\n{\n");
//            for (int i = 0; i < params.size(); i++) {
//                sb.append("this." + params.get(i) + " = " + params.get(i) + ";");
//                sb.append("\n");
//            }
//            sb.append("}");
            return sb.toString();
        } else {
            return "";
        }
    }

    private String getIncExec() {
        if ("Body".equals(NetType)) {
            return "RequestBody requestBody = RequestBody.create(MediaType.parse(\"application/json\"), JSON.toJSONString(request));\n" +
                    "return repository." + JkName + "(requestBody);";
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append("Map<String, Object> params = new HashMap<>();");
            sb.append("\n");
            for (int i = 0; i < params.size(); i++) {
                sb.append("params.put(\"" + params.get(i) + "\", request." + params.get(i) + ");");
                sb.append("\n");
            }
            sb.append("return repository." + JkName + "(params);");
            return sb.toString();
        }
    }


    /**
     * 读取模板文件中的字符内容
     *
     * @param fileName 模板文件名
     * @return
     */
    private String readTemplateFile(String fileName) {
        String path = MFinal.BAO_PATH + "template/" + fileName;
        InputStream in = null;
        in = this.getClass().getResourceAsStream(path);
        String content = "";
        try {
            content = new String(FileTools.readStream(in));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * 获取包名文件路径
     *
     * @return
     */
    private String getAppPath() {
        String appPath = project.getBasePath() + "/app/src/main/java/" + packagePath() + "/domain/usecase/";
        return appPath;
    }

    /**
     * 包名转化
     *
     * @return
     */
    private String packagePath() {
        return PackageName.replace(".", "/");
    }


//    /**
//     * 获取Repository
//     *
//     * @return
//     */
//    private String getRepository() {
//        String repos = project.getBasePath() + "/app/src/main/java/" + packagePath() + "/domain/" + DomianName + "Repository.java";
//        return repos;
//    }
}
